

import 'package:bookshelf/event/read_block_event.dart';

import '../event/inventory_event.dart';
import '../log/logger.dart';
import '../main.dart';
import '../util/analysis_book_rule.dart';

class ResultHandler{

  String ip = "";

  String result = "";
  bool isAnalyze = false;

  Set<(String,String,String)> set = {};

  dataReceived(hexString,ip){
    this.ip = ip;
    result += hexString;

    print('result=$result');

    if(settingEntity.log??false){
      Logger().write('result = $result\r\n');
    }

    if(!result.startsWith('DD')){
      result = '';
    }
    // //沾包
    // if(!hexString.startsWith('DD') && result.isNotEmpty){
    //   analyze();
    //   return;
    // }

    //询查标签
    if(result.length > 12 && result.substring(10,12) == "01"){
      analyze();
      return;
    }
    //读块
    if(result.length > 12 && result.substring(10,12)=="23"){
      analyzeBlock();
      return;
    }

  }

  analyze(){

    if(isAnalyze){
      return;
    }
    isAnalyze = true;
    //盘点结束指令
    //DD01EF0CFF0159000900ff10
    if(result.startsWith("DD") && result.length>=24 && result.substring(6,8) == '0C'){
      var data = set.toList();
      eventFactory.fire(InventoryEvent(data));
      result = "";
      set.clear();
      isAnalyze = false;
      return;
    }
    if(result.length>=38){
      set.add((result.substring(18,34),result.substring(8,10),ip));
      result = result.substring(38);
      isAnalyze = false;
      if(result.isNotEmpty){
        analyze();
      }
    }else{
      isAnalyze = false;
    }
  }

  analyzeBlock() {

    if(isAnalyze){
      return;
    }
    isAnalyze = true;
    if (result.length >= 24 && result.substring(12, 14) == "95") {
      result = '';
      isAnalyze = false;
      eventFactory.fire(ReadBlockEvent(null));
      return;
    }
    // String blockCount = result.substring(12, 14);
    // int count = hexToInt(blockCount);

    if (result.length >= 50) {
      var block = '';
      for(int i = 0; i<3;i++){
        int start = 16+(i+1)*2+i*8;
        block = block + result.substring(start,start+8);
      }
      var no = analysisBookRule(block);
      eventFactory.fire(ReadBlockEvent(no));

      result = result.substring(50);
      isAnalyze = false;
      if(result.isNotEmpty){
        analyzeBlock();
      }
    }else{
      isAnalyze = false;
    }
  }

  clear(){
    if(result.isNotEmpty){
      Logger().write('clearResult = $result\r\n');
    }
    result = '';
  }

}